//
//  RecommendViewController.m
//  UI_xiangmu
//
//  Created by dllo on 15/4/24.
//  Copyright (c) 2015年 dllo. All rights reserved."
//

#import "RecommendViewController.h"
#import "UpdateViewController.h"
#import "ClassifyViewController.h"
#import "AFHTTPRequestOperationManager.h"
#import "UIImageView+WebCache.h"
#import "MJRefresh.h"
#import "ClassifyDetailsModel.h"
#import "ClassifyDetailsCell.h"
#import "SearchViewController.h"
#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

@interface RecommendViewController ()
@property(nonatomic, retain)UITableView *hotRecommendTableView;
@property(nonatomic, retain)NSMutableArray *hotRecommendArr;//存model的数组
@property(nonatomic, assign)NSInteger pageindex;
@property(nonatomic, assign)NSInteger index;
@property(nonatomic, retain)NSMutableArray *picArr;// 用来装所有的图片数组
@property(nonatomic, retain)UIScrollView *headScrollView;
@property(nonatomic, retain)UIPageControl *headPageControl;
@property(nonatomic, retain)NSMutableArray *headRecommendArr;
@end

@implementation RecommendViewController

#pragma mark 初始化
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.hotRecommendArr = [NSMutableArray array];
        self.picArr = [NSMutableArray array];
        self.headRecommendArr = [NSMutableArray array];
    }
    return self;
}

#pragma mark 释放内存
-(void)dealloc
{
    [_hotRecommendTableView release];
    [_hotRecommendArr release];
    [_picArr release];
    [_headScrollView release];
    [_headPageControl release];
    [_hotRecommendArr release];
    [super dealloc];
}

#pragma mark viewDidLoad
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createRecommendView];
    [self addAndFresh];
}

#pragma mark 创建视图
- (void)createRecommendView
{
    UISegmentedControl *seg = [[UISegmentedControl alloc] initWithItems:@[@"热门推荐",@"每日更新",@"漫画分类"]];
    self.navigationItem.titleView = seg;
    seg.selectedSegmentIndex = 0;
    seg.backgroundColor = [UIColor whiteColor];
    [seg addTarget:self action:@selector(segClick:) forControlEvents:UIControlEventValueChanged];
    [seg release];
    //**********
    UIButton *rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    rightButton.frame = CGRectMake(300, 0, 50, 30);
    rightButton.layer.borderWidth = 1;
    rightButton.layer.cornerRadius = 8;
    [rightButton setTitle:@"搜索" forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(rightButtonItem) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithCustomView:rightButton] autorelease];
    //***********
    self.headPageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, 120, self.view.frame.size.width, 80)];
    self.headPageControl.pageIndicatorTintColor = [UIColor greenColor];
    self.headPageControl.numberOfPages = 4;
    [self.view addSubview:self.headPageControl];
    [_headPageControl release];
    //**********
    self.hotRecommendTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 210, WIDTH, 457) style:UITableViewStylePlain];
    self.hotRecommendTableView.rowHeight = 150;
    [self.view addSubview:self.hotRecommendTableView];
    [_hotRecommendTableView release];
    self.hotRecommendTableView.dataSource = self;
    self.hotRecommendTableView.delegate = self;
}

#pragma mark TableView代理必须实现的两个方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.hotRecommendArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *reuse = @"reuse";
    ClassifyDetailsCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse];
    if (!cell) {
        cell = [[[ClassifyDetailsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
    }
    ClassifyDetailsModel *hotRecommend = self.hotRecommendArr[indexPath.row];
    cell.classifyDetBookNameLabel.text = hotRecommend.BookName;
    cell.classifyDetBookDescriptionLabel.text = hotRecommend.BookDescription;
    NSURL *url = [NSURL URLWithString:hotRecommend.BookIconOtherURL];
    [cell.classifyDetBookIconOtherURLImageView sd_setImageWithURL:url];
    return cell;
}

#pragma mark TableView点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"跳转详情");
}

#pragma mark 解析热门推荐数据
- (void)hotRecommendData
{
    NSString *url = [NSString stringWithFormat:@"http://112.124.96.190:9090/manhuadaquan4appjobs/ComicHandle.ashx?method=recommend&pageindex=%ld&pagesize=41", self.pageindex];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSMutableArray *arr = responseObject;
        for (int i = 0; i < arr.count; i++) {
            if (i <= 3) {
                ClassifyDetailsModel *headRecommend = [[ClassifyDetailsModel alloc] init];
                [headRecommend setValuesForKeysWithDictionary:arr[i]];
                [self.headRecommendArr addObject:headRecommend];
                [self.picArr addObject:headRecommend.BookIconOtherURL];
            }else{
                ClassifyDetailsModel *hotRecommend = [[ClassifyDetailsModel alloc] init];
                [hotRecommend setValuesForKeysWithDictionary:arr[i]];
                [self.hotRecommendArr addObject:hotRecommend];
            }
        }
        id imageFirst = [self.picArr firstObject];
        id imageLast = [self.picArr lastObject];
        [self.picArr insertObject:imageLast atIndex:0];
        [self.picArr addObject:imageFirst];
        NSLog(@"%ld", self.picArr.count);
        
        
        self.headScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 200)];
        self.headScrollView.backgroundColor = [UIColor redColor];
        [self.view addSubview:self.headScrollView];
        [_headScrollView release];

        self.headScrollView.contentSize = CGSizeMake(self.view.frame.size.width * 6, 200);
        self.headScrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
        self.headScrollView.delegate = self;
        self.headScrollView.pagingEnabled = YES;
        for (int i = 0; i < self.picArr.count; i++) {
            NSURL *url = [NSURL URLWithString:[self.picArr objectAtIndex:i]];
            UIImageView *imageView = [[UIImageView alloc] init];
            [imageView sd_setImageWithURL:url];
            imageView.frame = CGRectMake(i * self.view.frame.size.width, 0, self.view.frame.size.width, 200);
            [self.headScrollView addSubview:imageView];
            [imageView release];
        }
        [self.hotRecommendTableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"请求失败");
        NSLog(@"%@", error);
    }];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.headScrollView.contentOffset.x == 0) {
        self.headScrollView.contentOffset = CGPointMake(self.view.frame.size.width * 5, 0);
    }else if (self.headScrollView.contentOffset.x == 375 * 5){
        self.headScrollView.contentOffset = CGPointMake(self.view.frame.size.width, 0);
    }
}











#pragma mark 下拉刷新上拉加载
- (void)addAndFresh
{
    [self.hotRecommendTableView addLegendHeaderWithRefreshingBlock:^{
        [self.hotRecommendArr removeAllObjects];
        self.pageindex = 0;
        [self hotRecommendData];
        [self.hotRecommendTableView reloadData];
        [self.hotRecommendTableView.header endRefreshing];
    }];
    [self.hotRecommendTableView.legendHeader beginRefreshing];
    [self.hotRecommendTableView addLegendFooterWithRefreshingBlock:^{
        self.pageindex++;
        [self hotRecommendData];
        [self.hotRecommendTableView reloadData];
        [self.hotRecommendTableView.footer endRefreshing];
    }];
}

#pragma mark 导航控制器右button点击方法
- (void)rightButtonItem
{
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}

#pragma mark 视图即将出现
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    UISegmentedControl *seg = (UISegmentedControl *)self.navigationItem.titleView;
    seg.selectedSegmentIndex = 0;
}

#pragma mark segment点击方法
-(void)segClick:(UISegmentedControl *)sander
{
    self.index = sander.selectedSegmentIndex;
    if (self.index == 1) {
        UpdateViewController *update = [[UpdateViewController alloc] init];
        [self.navigationController pushViewController:update animated:YES];
        [update release];
    }else if(self.index == 2){
        ClassifyViewController *classify = [[ClassifyViewController alloc] init];
        [self.navigationController pushViewController:classify animated:YES];
        [classify release];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
